package com.taxi.entity.common;

import cn.hutool.core.bean.BeanUtil;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@SuppressWarnings("unchecked")
public class RestResult<T> {

    private int code;

    private String msg;

    private T data;

    public RestResult(int code) {
        this.code = code;
    }

    public RestResult(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public RestResult(ResultEnum resultEnum) {
        this.code = resultEnum.getCode();
        this.msg = resultEnum.getMessage();
    }

    public static RestResult getEntity() {
        return new RestResult();
    }

    public static RestResult success() {
        RestResult result = new RestResult(ResultEnum.SUCCESS);
        return result;
    }

    public static RestResult fail() {
        RestResult result = new RestResult(ResultEnum.FAIL);
        return result;
    }

    public static <T> RestResult<T> success(T data) {
        RestResult result = new RestResult(ResultEnum.SUCCESS);
        result.setData(data);
        return result;
    }

    public static <T> RestResult<T> success(String key, Object value) {
        RestResult result = new RestResult(ResultEnum.SUCCESS);
        Map map = new HashMap();
        map.put(key, value);
        result.setData(map);
        return result;
    }

    public static <T> RestResult<T> build(ResultEnum resultEnum){
        return new RestResult<>(resultEnum);
    }

    public static <T> RestResult<T> failed(String message, ResultEnum resultEnum) {
        return new RestResult<>(resultEnum.getCode(), message);
    };

    public static <T> RestResult<T> failed(String message) {
        return failed(message, ResultEnum.FAIL);
    };

    public RestResult add(String key, Object value){
        RestResult<Map> result = new RestResult<>();
        Map params;
        result.setMsg(this.getMsg());
        result.setCode(this.getCode());
        if(Objects.isNull(this.getData())){
            params = new HashMap<>();
        }else{
            if(this.getData() instanceof Map){
                params = (Map) this.getData();
            }else{
                params = BeanUtil.beanToMap(this.getData(),false,true);
            }
        }
        params.put(key,value);
        result.setData(params);
        return result;
    }

    @JsonIgnore
    public boolean isSuccess() {
        return ResultEnum.SUCCESS.getCode() == this.getCode();
    }

}
